package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.UserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/13 11:26
 * @Version 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements UserLoginService {

    private final ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断是否游客登录
        //通过用户名查询用户数据
        //输入密码+salt  再来MD5
        //比较密码
        //生成token 构造返回数据
        Map<String,Object> map = new HashMap<>();
        if(!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())){
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,dto.getPhone()));
            if(apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            String salt = apUser.getSalt();
            String inputPs = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if(!inputPs.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
        }else {
            //游客登录  0
            map.put("token", AppJwtUtil.getToken(0l));
        }
        return ResponseResult.okResult(map);
    }


    }
